<template>
  <t-dialog :visible.sync="visible" header="编 辑" @confirm="handleConfirm" @cancel="handleCancel" @close="handleCancel">
    <t-form ref="formRef" :data="form" :rules="rules">
      <t-form-item label="用户名" name="username">
        <t-input v-model="form.username" placeholder="请输入用户名" clearable />
      </t-form-item>
      <t-form-item label="角 色" name="roleIds">
        <t-select multiple v-model="roleIds">
          <t-option v-for="(item, index) in roleOptions" :key="index" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
import { MessagePlugin, FormRules, } from 'tdesign-vue-next';
import { update, getById } from '@/api/userCenter/auth/user';
import { getList } from '@/api/userCenter/auth/role';
const visible = ref?.(false);
const loading = ref?.(false);
const formRef = ref?.(null);
const roleOptions = ref?.([]);
const roleIds = ref?.([]);

const form = ref?.({
  id: '',
  username: '',
  roleIds: '',
  title: '',
  content: ''
});
// 表单验证规则
const rules: FormRules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
};
const handleConfirm = async () => {
  if (!formRef) return;
  // 先进行表单验证
  const valid = await formRef?.value?.validate?.();
  if (valid !== true) {
    return;
  }

  form.value.roleIds = JSON?.stringify?.(roleIds.value)

  loading.value = true;
  try {

    await update?.(form.value);
    MessagePlugin?.success?.(`操作成功`);
    visible.value = false;
    emit?.('success');
    formRef?.value?.reset?.();

  } catch (t) {
  } finally {
    loading.value = false;
  }
};
const handleCancel = () => {
  visible.value = false;
};
const openDialog = async (id?: string) => {

  formRef?.value?.reset?.();
  roleIds.value = [];
  visible.value = true;
  getRoleOptions?.()
  if (id) {
    loading.value = true;
    form.value.id = id;

    const val = await getById?.(id);

    if (val && Object?.keys?.(val)?.length) {
      form.value = { ...form?.value, ...val, }

      roleIds.value = val?.roleIds;

    }
    loading.value = false;
  }
};

const getRoleOptions = async () => {

  roleOptions.value = [];

  roleOptions.value = await getList?.();

}

defineExpose({
  openDialog,
});
const emit = defineEmits(['success']);
</script>
<style lang="less" scoped>
/* 可以在这里添加自定义样式 */
</style>
